<template>
  <div class="route-list-container">
    <div class="page-header">
      <h1>我的路线</h1>
      <el-button type="primary" @click="createNewRoute">
        <el-icon><Plus /></el-icon>新增路线
      </el-button>
    </div>

    <div class="route-list">
      <el-empty v-if="routes.length === 0" description="暂无路线规划" />
      
      <el-card v-for="route in routes" :key="route.id" class="route-item" shadow="hover">
        <div class="route-card-header">
          <h3>{{ route.title }}</h3>
          <div class="route-actions">
            <el-button type="primary" size="small" @click="viewRoute(route.id)">查看</el-button>
            <el-button type="danger" size="small" @click="confirmDelete(route.id)">删除</el-button>
          </div>
        </div>
        
        <div class="route-info">
          <div class="route-meta">
            <p v-if="route.travelPlanId">
              <el-tag size="small">关联计划</el-tag>
              <span class="meta-value">{{ getPlanName(route.travelPlanId) }}</span>
            </p>
            <p>
              <el-tag size="small" type="info">创建时间</el-tag>
              <span class="meta-value">{{ formatDate(route.createdAt) }}</span>
            </p>
          </div>
          
          <div class="route-summary">
            <template v-if="route.routesData && route.routesData.length > 0">
              <div class="route-points">
                <div v-for="(segment, index) in route.routesData" :key="index" class="route-segment">
                  <div class="segment-point">{{ segment.origin }}</div>
                  <div class="segment-arrow">
                    <el-icon><ArrowRight /></el-icon>
                    <span class="transport-type">{{ getTransportTypeLabel(segment.transportType) }}</span>
                  </div>
                  <div class="segment-point">{{ segment.destination }}</div>
                </div>
              </div>
            </template>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, ArrowRight } from '@element-plus/icons-vue'
import { getRoutes, deleteRoute } from '../../api/route'
import { authUtils } from '../../utils/auth'
import { getTravelPlanById } from '../../api/travelPlan'

const router = useRouter()
const routes = ref([])
const planNames = ref({}) // 缓存计划名称

// 获取所有路线（按当前用户）
const fetchRoutes = async () => {
  try {
    const currentUser = authUtils.getCurrentUser()
    const params = currentUser?.id ? { userId: currentUser.id } : undefined
    const res = await getRoutes(params)
    if (res.success) {
      routes.value = res.data
      // 获取关联的旅行计划名称
      await fetchPlanNames()
    } else {
      ElMessage.error(res.message || '获取路线列表失败')
    }
  } catch (error) {
    console.error('获取路线列表失败:', error)
    ElMessage.error('获取路线列表失败')
  }
}

// 获取关联的旅行计划名称
const fetchPlanNames = async () => {
  const planIds = new Set()
  routes.value.forEach(route => {
    if (route.travelPlanId) {
      planIds.add(route.travelPlanId)
    }
  })
  
  for (const planId of planIds) {
    try {
      const plan = await getTravelPlanById(planId)
      if (plan && plan.title) {
        planNames.value[planId] = plan.title
      }
    } catch (error) {
      console.error(`获取计划 ${planId} 失败:`, error)
    }
  }
}

// 获取计划名称
const getPlanName = (planId) => {
  return planNames.value[planId] || '未命名计划'
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 获取交通方式标签
const getTransportTypeLabel = (type) => {
  const types = {
    'walking': '步行',
    'transit': '公交',
    'driving': '驾车',
    'riding': '骑行',
    'flying': '飞机',
    'train': '火车',
    'other': '其他'
  }
  return types[type] || type
}

// 查看路线详情
const viewRoute = (id) => {
  router.push(`/route-planning?routeId=${id}`)
}

// 创建新路线
const createNewRoute = () => {
  router.push('/route-planning')
}

// 确认删除
const confirmDelete = (id) => {
  ElMessageBox.confirm('确定要删除这条路线吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteRoute(id)
      if (res.success) {
        ElMessage.success('删除成功')
        await fetchRoutes()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除路线失败:', error)
      ElMessage.error('删除路线失败')
    }
  }).catch(() => {})
}

onMounted(() => {
  fetchRoutes()
})
</script>

<style scoped>
.route-list-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #409EFF;
}

.route-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.route-item {
  margin-bottom: 0;
}

.route-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.route-card-header h3 {
  margin: 0;
  color: #303133;
}

.route-actions {
  display: flex;
  gap: 8px;
}

.route-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.route-meta {
  display: flex;
  gap: 16px;
}

.route-meta p {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.meta-value {
  color: #606266;
}

.route-summary {
  margin-top: 8px;
}

.route-points {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.route-segment {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.segment-point {
  padding: 4px 8px;
  background-color: #ecf5ff;
  border-radius: 4px;
  color: #409EFF;
  flex: 1;
}

.segment-arrow {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
}

.transport-type {
  font-size: 12px;
  margin-top: 2px;
}
</style>